package titt.io.encoding;

import titt.type.Type;

public class CompositeEncoder implements Encoder {

	private static final Encoder EMPTY = new Encoder() {

		@Override
		public byte[] encode(Type t, Object o) {
			return null;
		}

		@Override
		public boolean isEncodeable(Type t) {
			return false;
		}
		
	};
	
	private Encoder pri, sec;
	
	public CompositeEncoder(Encoder... encs) {
		this(encs.length == 0? new Encoder[]{EMPTY} : encs, 0);
	}
	
	private CompositeEncoder(Encoder[] encs, int off) {
		this(encs[off], off < encs.length - 1? new CompositeEncoder(encs, off + 1) : EMPTY);
	}
	
	private CompositeEncoder(Encoder pri, Encoder sec) {
		this.pri = pri;
		this.sec = sec;
	}
	
	@Override
	public byte[] encode(Type t, Object o) {
		if(pri.isEncodeable(t))
			return pri.encode(t, o);
		else
			return sec.encode(t, o);
	}
	
	@Override
	public boolean isEncodeable(Type t) {
		return pri.isEncodeable(t) || sec.isEncodeable(t);
	}	
}
